﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
using System.Runtime.InteropServices;

namespace XCBPM.Mobile.Common
{
    public class UserDomainCheck
    {
        private WindowsImpersonationContext impersonationContext;
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);
        public bool impersonateValidUser(string userName, string domain, string password)
        {
            IntPtr zero = IntPtr.Zero;
            IntPtr hNewToken = IntPtr.Zero;
            if (LogonUser(userName, domain, password, 2, 0, ref zero) != 0)
            {
                if (DuplicateToken(zero, 2, ref hNewToken) != 0)
                {
                    this.impersonationContext = new WindowsIdentity(hNewToken).Impersonate();
                    return (this.impersonationContext != null);
                }
                return false;
            }
            return false;
        }

        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
        public static extern int LogonUser(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
        public void undoImpersonation()
        {
            this.impersonationContext.Undo();
        }
    }
}